package com.dzz.sjgl.controller;

import com.dzz.sjgl.entity.UserInfo;
import com.dzz.sjgl.service.IUserService;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;

/**
 * @author KRIC
 * @ClassName LocatoinControlller
 * @Date: 2018/9/18 10:52
 * @Description: 通过地址获取坐标信息
 */
@Controller
@RequestMapping("/user")
public class UserController {

    private final IUserService userService;

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    public UserController(IUserService userService) {
        this.userService = userService;
    }

    @ApiOperation(value = "登录")
    @ResponseBody
    @PostMapping("/login")
    public boolean login(String login, String password) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(login, password);
        try {
            subject.login(token);
            UserInfo userInfo = userService.getUserByLogin(login);
//            Cookie name = new Cookie("name", URLEncoder.encode(userInfo.getName(), "UTF-8"));
//            Cookie loginC = new Cookie("login", URLEncoder.encode(userInfo.getLogin(), "UTF-8"));
//            Cookie lastLogin = new Cookie("lastLogin", URLEncoder.encode(userInfo.getThisLogin() == null ? "" : userInfo.getThisLogin().toString(), "UTF-8"));
//            Cookie userId = new Cookie("userId", String.valueOf(userInfo.getId()));
//            resp.addCookie(name);
//            resp.addCookie(loginC);
//            resp.addCookie(userId);
//            resp.addCookie(lastLogin);
            userInfo.setLastLogin(userInfo.getThisLogin());
            userInfo.setThisLogin(new Date());
            userService.save(userInfo);
        } catch (AuthenticationException e) {
            token.clear();
            logger.error(e.getMessage());
            logger.info(login + "登录失败");
            return false;
        }
        logger.info(login + "登录成功");
        return true;
    }

    @ApiOperation(value = "注销")
    @ResponseBody
    @GetMapping("/logout")
    public boolean logout() {
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.logout();
        } catch (Exception e) {
            logger.error(e.getMessage());
            return false;
        }
        return true;
    }

    @ApiOperation(value = "注册")
    @ResponseBody
    @PostMapping("/add")
    public String add(UserInfo userInfo) {
        try {
            if (isExist(userInfo.getLogin())) {
                logger.info("用户已存在");
                return "用户已存在";
            } else {
                userInfo.setCreateTime(new Date());
                userService.save(userInfo);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            logger.info("注册失败");
            return "注册失败";
        }
        logger.info("注册成功");
        return "注册成功";
    }


    @ApiOperation(value = "用户是否存在")
    @ResponseBody
    @GetMapping("/isExist")
    public boolean isExist(String login) {
        UserInfo userInfo = userService.getUserByLogin(login);
        return userInfo != null;
    }

    @ApiOperation(value = "获取当前登录用户信息")
    @ResponseBody
    @GetMapping("/getUserInfo")
    public UserInfo getUserInfo() {
        return (UserInfo) SecurityUtils.getSubject().getPrincipal();
    }


    @ApiOperation(value = "获取所有用户列表")
    @ResponseBody
    @GetMapping("/getList")
    public Page<UserInfo> getList(int pageNum, int pageSize, String name, String login) {
        UserInfo userInfo = (UserInfo) SecurityUtils.getSubject().getPrincipal();
        Page<UserInfo> page = null;
        if ("admin".equals(userInfo.getLogin())) {
            if (StringUtils.isEmpty(name) && StringUtils.isEmpty(login)) {
                page = userService.findAll(pageNum, pageSize);
            } else {
                page = userService.findAllByQuery(pageNum, pageSize, name, login);
            }
        }
        return page;
    }

}
